/**
 * 
 */
package com.armail.client.controller.impl;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;

import javax.ws.rs.core.MediaType;

import com.armail.client.controller.DraftsController;
import com.armail.client.controller.DraftsControllerListener;
import com.armail.client.di.Context;
import com.armail.client.dto.Mail;
import com.armail.client.view.DraftsView;
import com.armail.client.view.DraftsViewListener;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

/**
 * @author arpit
 *
 */
public class DraftsControllerImpl extends ControllerImpl implements DraftsController, DraftsViewListener{

	protected final Collection<DraftsControllerListener> listeners = new LinkedHashSet<DraftsControllerListener>();
	private final DraftsView draftsView;
	private static final String REST_URI = "http://localhost:8080/com-armail-server/";
	private static final String GET_DRAFT_MAILS = "/mails/getDraftmails/";
	
	@Inject
	public DraftsControllerImpl(Injector injector, DraftsView draftsView) {
		super(injector);
		this.draftsView =  draftsView;
		this.draftsView.addListener(this);
	}
	
	public List<Mail> getDraftMails() {
		ClientConfig config = new DefaultClientConfig();  
        Client client = Client.create(config);  
        WebResource resource = client.resource(REST_URI);  
        
        WebResource employeeResource = resource.path("/rest/").path(GET_DRAFT_MAILS).path(Context.getUser().getId()+""); 
        final ClientResponse response = employeeResource.accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
        return response.getEntity(new GenericType<List<Mail>>() {});
	}
	
	@Override
	public void activate() {
		draftsView.setModel(getDraftMails());
		draftsView.attach();
	}
	
	@Override
	public void deactivate() {
		draftsView.detach();
	}

	@Override
	public void onDraftSelected(Mail selectedMail) {
		for (DraftsControllerListener l : listeners) {
			l.onDraftSelected(selectedMail);
		}
	}

	@Override
	public void addListener(DraftsControllerListener listener) {
		this.listeners.add(listener);
	}

	@Override
	public void removeListener(DraftsControllerListener listener) {
		this.listeners.add(listener);
	}

}
